

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class Client {

    public static void main(String arg[]) {
        testDownload();
    }

    public static void testUpload() {
        String filePath = "D:" + File.separator + "beauty.jpg";
        Client client = new Client();
        client.uploadFile(filePath);
    }

    public static void testDownload() {
        Client client = new Client();
        client.downloadFile();
    }

    public void uploadFile(String filePath) {
        try {
            File file = new File(filePath);
            String fileName = file.getName();
            long fileLength = file.length();
            System.out.println("客户端待上传文件：" + fileName + "，其大小为：" + fileLength);
            FileInputStream fileInputStream = new FileInputStream(filePath);
            Socket socket = new Socket(Config.ip, Config.port);
            OutputStream outputStream = socket.getOutputStream();
            DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
            dataOutputStream.writeUTF(fileName);
            dataOutputStream.writeLong(fileLength);
            dataOutputStream.flush();

            byte[] buf = new byte[1024 * 1];
            int len = 0;
            while ((len = fileInputStream.read(buf)) != -1) {
                dataOutputStream.write(buf, 0, len);
            }

            dataOutputStream.flush();
            fileInputStream.close();
            socket.close();
        } catch (Exception e) {
            System.out.println(e.toString());
        }
    }

    public void downloadFile() {
        try {
            Socket socket = new Socket(Config.ip, Config.port);
            InputStream inputStream = socket.getInputStream();
            DataInputStream dataInputStream = new DataInputStream(inputStream);
            String fileName = dataInputStream.readUTF();
            long fileLength = dataInputStream.readLong();
            System.out.println("客户端下载文件：" + fileName + "，其大小为：" + fileLength);

            String fileDir = "D:";
            String filePath = fileDir + File.separator + fileName;

            FileOutputStream fileOutputStream = new FileOutputStream(filePath);

            byte[] buf = new byte[1024 * 1];
            int len = 0;
            while ((len = dataInputStream.read(buf)) != -1) {
                fileOutputStream.write(buf, 0, len);
            }
            fileOutputStream.flush();
            fileOutputStream.close();
            dataInputStream.close();
            socket.close();
        } catch (Exception e) {
            System.out.println(e.toString());
        }
    }

}

